<!-- 关键物料信息弹窗 -->
<template>
  <el-dialog custom-class="keyPartModalDialog" append-to-body :title="title" :visible.sync="visible" @close="close" width="80%" top="5vh">
    <div class="menuBtnGroups" v-if="!readOnlyPage">
      <el-button type="primary" @click="addMaterial">添加物料</el-button>
      <el-button type="primary" @click="addBom">添加BOM</el-button>
      <el-button type="danger" icon="el-icon-delete" @click="handleDelete">删除</el-button>
    </div>
    <vxe-grid ref="crud" v-bind="gridOptions" v-loading="loading" :data="data">
      <template #componentWorkOrderNoRequire="{ row, rowIndex }">
        <el-input placeholder="请输入工单号" size="small" v-model="row.componentWorkOrderNoRequire" class="input-with-select">
          <el-button slot="append" icon="el-icon-search" @click="openCommonModalWorkOrder(row, rowIndex)"></el-button>
        </el-input>
      </template>
      <template #quantity="{ row }">
        <!-- :precision="10" -->
        <el-input-number v-model="row.quantity" size="small" name="quantity" :controls="false" style="width: 100%" placeholder="请输入单位用量"></el-input-number>
      </template>
      <template #action="{ row, rowIndex }">
        <el-button type="text" size="small" v-if="!readOnlyPage" @click="handleAddMaterial(row, rowIndex)">添加替代料</el-button>
      </template>
    </vxe-grid>
    <div slot="footer" class="dialog-footer" v-if="!readOnlyPage">
      <el-button type="primary" size="small" icon="el-icon-circle-plus-outline" @click="submitForm">保 存</el-button>
      <el-button size="small" icon="el-icon-circle-close" @click="close">取 消</el-button>
    </div>
    <!-- 添加物料 -->
    <addMaterialDialog :showSection="false" v-if="showMaterialDialog" ref="material" :visible.sync="showMaterialDialog" :productInfoList="data"></addMaterialDialog>
    <!-- 添加BOM -->
    <addBomDialog :showSection="false" v-if="showBomDialog" ref="addBom" :visible.sync="showBomDialog" :productInfoList="data"></addBomDialog>
    <!-- 物料基础数据 弹框 -->
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </common-modal-template>
    <global-modal-template :visibile.sync="visibile" :option="addTableOption" @getSelectedRows="getAddSelectedRows" :key="timer" @newKey="newKey"> </global-modal-template>
  </el-dialog>
</template>

<script>
import { mapState } from 'vuex';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import GlobalModalTemplate from '@/components/common-modal-template/global-modal-template.vue';
import { checkKeyMaterialConfig } from '@/api/product/productrouteManage';
import { getList as getBomList } from '@/api/admin/bom';
import { writeWorkOrder, getProductMaterialConfig } from '@/api/product/workorder';
import addMaterialDialog from '@/views/product/components/addMaterial.vue';
import addBomDialog from '@/views/product/components/addBom.vue';
export default {
  name: 'KeyPartModal',
  components: {
    CommonModalTemplate,
    GlobalModalTemplate,
    addMaterialDialog,
    addBomDialog
  },
  props: {
    config: {
      require: true,
      default: () => {}
    }
  },
  data() {
    return {
      gridOptions: {
        border: true,
        showOverflow: true,
        height: 450,
        scrollY: {
          enabled: true,
          gt: 0
        },
        columns: [
          { type: 'checkbox', width: 50 },
          { type: 'seq', title: '序号', width: 50 },
          { field: 'partNo', title: '物料编码', showOverflow: 'title' },
          { field: 'partName', title: '物料名称', showOverflow: 'title' },
          { field: 'partSpec', title: '物料规格', showOverflow: 'title' },
          { field: 'componentWorkOrderNoRequire', title: '工单号', slots: { default: 'componentWorkOrderNoRequire' } },
          { field: 'quantity', title: '单位用量', slots: { default: 'quantity' } },
          { field: 'replacePartNo', title: '替代料编码', width: 100, showOverflow: 'title' },
          { field: 'replacePartSpec', title: '替代料规格', width: 100, showOverflow: 'title' },
          { field: 'replaceQuantity', title: '替代料用量', width: 100, showOverflow: 'title' },
          { field: 'action', title: '操作', width: 100, slots: { default: 'action' } }
        ]
      },
      showMaterialDialog: false,
      showBomDialog: false,
      selectionList: [],
      visibile: false,
      title: '',
      loading: false,
      data: [],
      page: {
        pageSize: 1000,
        currentPage: 1,
        total: 0
      },
      modalName: '',
      addTableOption: {},
      tableOption: {},
      commonTableOption: {}, //公用模态框配置信息
      timer: new Date().getTime(), //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
      selectIndex: 0,
      selectionList: [],
      rowIndex: ''
    };
  },
  computed: {
    ...mapState({
      currentStationInfo: (state) => state.design.currentStationInfo
    }),
    routePath() {
      return this.$route.path;
    },
    // 查看页面 只读
    readOnlyPage() {
      if (this.routePath.endsWith('pdesign') || this.routePath.endsWith('gdesign')) {
        return false;
      } else {
        return true;
      }
    },
    // 是否工单工艺路线设计器
    isGdEditorPage() {
      if (this.$route.path.endsWith('pdesign') || this.$route.path.endsWith('pread')) {
        return false;
      } else if (this.$route.path.endsWith('gdesign') || this.$route.path.endsWith('gread')) {
        return true;
      }
    }
  },
  watch: {
    config: {
      handler(value) {
        let copyData = this._cloneDeep(value);
        this.data = copyData.data;
        this.title = copyData.title;
        this.visible = copyData.visible;
        this.loading = copyData.loading;
      },
      deep: true
    }
  },
  mounted() {
    this.data = this.config.data;
    this.title = this.config.title;
    this.visible = this.config.visible;
    this.loading = this.config.loading;
  },
  methods: {
    handleDelete() {
      this.selectionList = this.$refs.crud.getCheckboxRecords();
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let partMasterIds = this.selectionList.map((s) => s.partMasterId);
        let partNames = this.selectionList.map((s) => s.partName).join(',');
        this.data = this.data.filter((d) => !partMasterIds.includes(d.partMasterId));
        this.$message({
          type: 'success',
          message: `物料名称为${partNames}删除成功!`
        });
        this.$refs.crud.clearSelected();
      });
    },
    selectionChange(list) {
      this.selectionList = list;
    },

    // 添加物料
    addMaterial() {
      this.showMaterialDialog = true;
      this.$nextTick(() => {
        this.$refs.material.initData([]);
      });
    },
    getAddSelectedRows(rowData) {
      switch (this.modalName) {
        case 'tjwlModal':
          let repeatData = rowData.filter((row) => this.data.map((d) => d.partMasterId).includes(row.id)).map((r) => r.name);
          let noRepeatData = rowData.filter((row) => !this.data.map((d) => d.partMasterId).includes(row.id));
          if (repeatData && repeatData.length > 0) {
            this.$message.warning(`物料${repeatData.join(',')}已添加，请勿重复操作`);
          }
          let data = noRepeatData.map((d) => {
            return {
              quantity: 0,
              partName: d.name,
              partNo: d.partNo,
              partModel: d.partModel,
              partMasterId: d.id
            };
          });
          this.data = this.data.concat(data);
          this.visibile = false;
          break;
        default:
          break;
      }
    },
    // 添加BOM
    addBom() {
      this.showBomDialog = true;
      this.$nextTick(() => {
        this.$refs.addBom.initData(
          [],
          [
            {
              bomId: this.$route.query.bomId,
              partNo: this.$route.query.partNo,
              partName: this.$route.query.partName,
              partMasterId: this.$route.query.partMasterId,
              partModel: ''
            }
          ]
        );
      });
    },
    openCommonModalWorkOrder(row, index) {
      console.log(row, index);
      this.modalName = 'workOrderModal';
      this.selectIndex = index;
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择工单信息（双击进行选择）',
        url: '/api/mes-product/work-order/page',
        rowSelectionType: 'single',
        page: true,
        menu: false,
        editBtn: false,
        menuWidth: 100,
        searchLabelWidth: 100,
        query: {
          productPartNo: row.partNo
        },
        columnDefs: [
          {
            label: '生产工单',
            prop: 'workOrderNo',
            search: true
          },
          {
            label: '工单类型',
            prop: 'type',
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=order_type',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          },
          {
            label: '工单计划数量',
            prop: 'planQuantity'
          },
          {
            label: '产品编码',
            prop: 'productPartNo'
          },
          {
            label: '产品名称',
            prop: 'productPartName'
          },
          {
            label: '产品型号',
            prop: 'productPartModel'
          }
        ]
      };
    },
    openBomPart(bomList, bomId) {
      this.modalName = 'bomModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择BOM物料信息（双击进行选择）',
        url: '/api/mes-admin/bom/detail/part-page',
        isPage: true,
        index: true,
        selection: true,
        rowSelectionType: 'multiple',
        columnDefs: [
          {
            label: '名称',
            prop: 'name',
            search: true
          },
          {
            label: '编码',
            prop: 'partNo',
            search: true
          },
          {
            label: '类型',
            prop: 'categoryId',
            type: 'tree',
            dicUrl: '/api/mes-admin/part-category/tree',
            props: {
              label: 'title',
              value: 'id'
            }
          },
          {
            label: '型号',
            prop: 'partModel'
          },
          {
            label: '用量',
            prop: 'unitQty'
          },
          {
            label: 'BOM版本',
            prop: 'bomId',
            search: true,
            type: 'select',
            dicData: bomList,
            searchValue: bomId,
            hide: true
          }
        ]
      };
    },
    getProductMaterialByOrderId() {
      getProductMaterialConfig(this.$route.query.workOrderId).then((res) => {
        let data = res.data.data;
        this.data = this._get(data, 'materialControls', []);
        if (this.data === null) {
          this.data = [];
        }
        this._forEach(this.data, (item) => {
          try {
            item.replacementPartName = (JSON.parse(item.replacementPartnos) || []).map((item) => item.partName).join(',');
          } catch (error) {
            console.log('error', error);
          }
        });
      });
    },
    /**
     * 添加替代料
     */
    async handleAddMaterial(row, index) {
      this.selectIndex = index;
      const params = {
        bomPartNo: this.$route.query.partNo,
        bomDetailPartNo: row.partNo
      };
      getBomList(1, 10000, { productPartNo: this.$route.query.partNo, sourceType: 'ERP', isAll: true }).then((res) => {
        let bomList = this._get(res, 'data.data.records', []);
        if (bomList.length > 0) {
          bomList = this._map(bomList, (item) => {
            return {
              label: item.bomVersion,
              value: item.id
            };
          });
          let bomId = this._get(bomList, '[0].value', '');
          this.openReplacement(params, { bomId, bomList });
        } else {
          this.$message({
            type: 'warning',
            message: '请先配置相应的产品BOM！'
          });
        }
      });
    },
    openReplacement(query, { bomId, bomList }) {
      this.modalName = 'replaceModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '添加替代料 (双击进行选择)',
        url: '/api/mes-admin/bom/part/replacement/list',
        isPage: true,
        index: true,
        emptyBtn: false,
        query,
        selection: false,
        tableTitle: '替代料',
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: 'BOM版本',
            search: true,
            clearable: false,
            searchClearable: false,
            type: 'select',
            prop: 'bomId',
            dicData: bomList,
            searchValue: bomId,
            hide: true,
            searchLabelWidth: 90,
            searchRules: [
              {
                required: true,
                message: '请先选择BOM版本',
                trigger: 'change'
              }
            ]
          },
          {
            label: '名称',
            prop: 'replacePartName',
            search: true
          },
          {
            label: '编码',
            prop: 'replacePartNo',
            search: true
          },
          {
            label: '类型',
            prop: 'replacePartType',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            dicUrl: '/api/blade-system/dict/dictionary?code=part_type'
          },
          {
            label: '规格',
            prop: 'replacePartSpec'
          },
          {
            label: '用量',
            prop: 'replaceQuantity'
          }
        ]
      };
    },
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'partModal':
          for (let i = 0; i < rowData.length; i++) {
            this.data.push({
              $cellEdit: true,
              partMasterId: rowData[i].id,
              partNo: rowData[i].partNo,
              partName: rowData[i].name,
              partModel: rowData[i].partModel,
              quantity: undefined
            });
          }
          break;
        case 'bomModal':
          for (let i = 0; i < rowData.length; i++) {
            this.data.push({
              $cellEdit: true,
              partMasterId: rowData[i].id,
              partNo: rowData[i].partNo,
              partName: rowData[i].name,
              partModel: rowData[i].partModel,
              quantity: rowData[i].unitQty
            });
          }
          break;
        case 'replaceModal':
          const index = this.selectIndex;
          this.$set(this.data[index], 'replacePartNo', rowData.replacePartNo);
          this.$set(this.data[index], 'replacePartSpec', rowData.replacePartSpec);
          this.$set(this.data[index], 'replaceQuantity', rowData.replaceQuantity);
          break;
        case 'workOrderModal':
          this.$set(this.data[this.selectIndex], 'componentWorkOrderIdRequire', rowData.id);
          this.$set(this.data[this.selectIndex], 'componentWorkOrderNoRequire', rowData.workOrderNo);
          break;
        default:
          break;
      }
    },
    submitForm() {
      let deepCloneCurrentStationInfo = JSON.parse(JSON.stringify(this.currentStationInfo));
      if (this.data.length > 0) {
        let hasQuantity = this.data.every((d) => d.quantity > 0);
        if (!hasQuantity) {
          this.$message.warning('物料数量不能为0！');
          return;
        }
      }
      deepCloneCurrentStationInfo.assembleKeyMaterialConfigList = this.data.map((d) => {
        return {
          componentWorkOrderNoRequire: d.componentWorkOrderNoRequire,
          componentWorkOrderIdRequire: d.componentWorkOrderIdRequire,
          partModel: d.partModel,
          partName: d.partName,
          partSpec: d.partSpec,
          partMasterId: d.partMasterId, // 物料id
          partNo: d.partNo, //物料编码
          partSpec: d.partSpec, //物料规格
          quantity: d.quantity, //数量
          replacePartNo: d.replacePartNo,
          replacePartSpec: d.replacePartSpec,
          replaceQuantity: d.replaceQuantity
        };
      });
      if (deepCloneCurrentStationInfo.id) {
        let params = {
          workOrderId: this.isGdEditorPage ? this.$route.query.workOrderId : '',
          routeCode: deepCloneCurrentStationInfo.routeCode,
          processType: this.isGdEditorPage ? 'WORKORDER' : 'PART',
          newKeyMaterialList: deepCloneCurrentStationInfo.assembleKeyMaterialConfigList
        };
        checkKeyMaterialConfig(params).then((res) => {
          // 重新设置当前选中工站信息
          this.$store.commit('design/setCurrentStationInfo', deepCloneCurrentStationInfo);
          // 重新设置所有有效工序信息
          this.$store.commit('design/changeAllActiveStations', deepCloneCurrentStationInfo);
          this.close();
        });
      } else {
        // 重新设置当前选中工站信息
        this.$store.commit('design/setCurrentStationInfo', deepCloneCurrentStationInfo);
        // 重新设置所有有效工序信息
        this.$store.commit('design/changeAllActiveStations', deepCloneCurrentStationInfo);
        this.close();
      }
    },
    // 重新加载公用表格弹窗组件
    newKey() {
      this.timer = new Date().getTime();
    },
    close() {
      this.$emit('close');
    }
  }
};
</script>
<style lang="scss" scoped>
::v-deep .keyPartModalDialog {
  .el-dialog__body {
    padding: 10px;
    .menuBtnGroups {
      margin-bottom: 10px;
    }
  }
  .el-dialog__footer {
    padding: 0 10px 10px;
  }
}
</style>
